package web.fabrimind.pm.service.impl;

import java.util.List;
import web.fabrimind.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import web.fabrimind.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import web.fabrimind.pm.domain.BomDetail;
import web.fabrimind.pm.mapper.BomMapper;
import web.fabrimind.pm.domain.Bom;
import web.fabrimind.pm.service.IBomService;

/**
 * BOMService业务层处理
 * 
 * @author zhihui
 * @date 2025-03-25
 */
@Service
public class BomServiceImpl implements IBomService 
{
    @Autowired
    private BomMapper bomMapper;

    /**
     * 查询BOM
     * 
     * @param bomId BOM主键
     * @return BOM
     */
    @Override
    public Bom selectBomByBomId(Long bomId)
    {
        return bomMapper.selectBomByBomId(bomId);
    }

    /**
     * 查询BOM列表
     * 
     * @param bom BOM
     * @return BOM
     */
    @Override
    public List<Bom> selectBomList(Bom bom)
    {
        return bomMapper.selectBomList(bom);
    }

    /**
     * 新增BOM
     * 
     * @param bom BOM
     * @return 结果
     */
    @Transactional
    @Override
    public int insertBom(Bom bom)
    {
        bom.setCreateTime(DateUtils.getNowDate());
        int rows = bomMapper.insertBom(bom);
        insertBomDetail(bom);
        return rows;
    }

    /**
     * 修改BOM
     * 
     * @param bom BOM
     * @return 结果
     */
    @Transactional
    @Override
    public int updateBom(Bom bom)
    {
        bom.setUpdateTime(DateUtils.getNowDate());
        bomMapper.deleteBomDetailByBomId(bom.getBomId());
        insertBomDetail(bom);
        return bomMapper.updateBom(bom);
    }

    /**
     * 批量删除BOM
     * 
     * @param bomIds 需要删除的BOM主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBomByBomIds(Long[] bomIds)
    {
        bomMapper.deleteBomDetailByBomIds(bomIds);
        return bomMapper.deleteBomByBomIds(bomIds);
    }

    /**
     * 删除BOM信息
     * 
     * @param bomId BOM主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBomByBomId(Long bomId)
    {
        bomMapper.deleteBomDetailByBomId(bomId);
        return bomMapper.deleteBomByBomId(bomId);
    }

    /**
     * 新增BOM明细信息
     * 
     * @param bom BOM对象
     */
    public void insertBomDetail(Bom bom)
    {
        List<BomDetail> bomDetailList = bom.getBomDetailList();
        Long bomId = bom.getBomId();
        if (StringUtils.isNotNull(bomDetailList))
        {
            List<BomDetail> list = new ArrayList<BomDetail>();
            for (BomDetail bomDetail : bomDetailList)
            {
                bomDetail.setBomId(bomId);
                list.add(bomDetail);
            }
            if (list.size() > 0)
            {
                bomMapper.batchBomDetail(list);
            }
        }
    }
}
